"""
购物车接口层
"""
import datetime
import logging

from db.db_handler import get_goods_info, save, set_goods_info

from lib.common import pretty_print

logger = logging.getLogger(__name__)


def goods_list_interface():
    """打印商品列表，返回商品字典"""
    # 读取商品字典
    goods_info = get_goods_info()
    if not goods_info:
        return None
    title_list = ['商品名', '商品价格', '商品库存']
    data_list = [[key, goods_info[key][0], goods_info[key][1]] for key in goods_info]
    pretty_print(title_list, data_list, auto_index=True)  # 美化打印
    return goods_info


def go_shopping_interface(user_dict, goods_info, goods_name, goods_num, choice):
    """
    购物接口
    :param user_dict: 当前用户字典
    :param goods_info: 商品字典
    :param goods_name: 选购的商品名
    :param goods_num: 选购的商品数量
    :param choice: 选项：1 直接购买 ;2加入购物车
    :return: None
    """
    total_amount = goods_info[goods_name][0] * goods_num  # 总金额
    # 直接购买
    if choice == '1' and total_amount > user_dict['balance']:
        print('账户余额不足！')
    if choice == '1':
        user_dict['balance'] -= total_amount  # 扣款
        user_dict['flow'].append(  # 记录流水
            f"{datetime.datetime.now()} 用户{user_dict['username']}购买{goods_name}*{goods_num}花费{total_amount}元")
        save(user_dict)  # 保存数据
        goods_info[goods_name][1] -= goods_num  # 减少对应库存
        set_goods_info(goods_info)  # 保存商品数据
        logger.info(f"用户{user_dict['username']}购买{goods_name}*{goods_num}花费{total_amount}元")
        logger.info(f"商品{goods_name}库存-{goods_num}")
        return
    # 加入购物车
    flag = True  # 判断购物车中是否已经存在该商品
    for index, goods in enumerate(user_dict['shop_cart']):
        if goods[0] == goods_name:
            user_dict['shop_cart'][index][2] += goods_num
            user_dict['shop_cart'][index][3] += total_amount
            flag = False
            break

    if flag:  # 购物车中不存在该商品
        user_dict['shop_cart'].append([goods_name, goods_info[goods_name][0], goods_num, total_amount])
    save(user_dict)  # 保存用户数据

    logger.info(f"用户{user_dict['username']}购物车加入{goods_name}*{goods_num}")
    goods_info[goods_name][1] -= goods_num
    set_goods_info(goods_info)  # 保存商品数据
    logger.info(f"商品{goods_name}库存-{goods_num}")


def get_goods_through_no(goods_info, goods_no):
    """通过商品序号获得商品名字"""
    for index, goods_name in enumerate(goods_info):
        if index + 1 == int(goods_no):
            return goods_name


def shop_cart_list_interface(user_dict):
    """打印购物车列表"""
    if not user_dict['shop_cart']:
        return False
    title_list = ['商品名', '商品价格', '数量', '总价格']
    data_list = user_dict['shop_cart']
    all_total_amount = 0
    for i in user_dict['shop_cart']:
        all_total_amount += i[3]
    print(f" 购物车详情 ".center(30, '*'))
    pretty_print(title_list, data_list, auto_index=True)  # 美化输出
    print(f" 购物车总价格: {all_total_amount}  ".center(30, '*'))
    print(f" 当前用户:{user_dict['username']}  当前余额: {user_dict['balance']} ".center(30, '*'))
    return True


def cart_management_interface(user_dict, goods_no=None, goods_num=None, clear=False):
    """
    购物车管理接口
    :param user_dict: 用户字典
    :param goods_no: 删除的商品序号 默认None
    :param goods_num: 删除的商品数量 默认None
    :param clear: 是否清空购物车 默认为False
    :return:
    """

    goods_info = get_goods_info()
    # 全部删除
    if clear:
        for goods in user_dict['shop_cart']:
            goods_info[goods[0]][1] += goods[2]
        user_dict['shop_cart'].clear()
        save(user_dict)
        set_goods_info(goods_info)
        return

        # 指定删除
    user_dict['shop_cart'][goods_no][2] -= goods_num
    user_dict['shop_cart'][goods_no][3] -= goods_num * user_dict['shop_cart'][goods_no][1]
    if user_dict['shop_cart'][goods_no][2] == 0:
        user_dict['shop_cart'].pop(goods_no)
    save(user_dict)

    goods_info[user_dict['shop_cart'][goods_no][0]][1] += goods_num
    set_goods_info(goods_info)


def cart_payment_interface(user_dict, goods_no=None, goods_num=None, all=False):
    """
    购物车结算接口
    :param user_dict: 用户字典
    :param goods_no: 购物车中商品序号 默认None
    :param goods_num: 结算的商品数量 默认None
    :param all: 是否全部结算，默认False
    :return:
    """
    # 全部结算
    if all:
        total_amount = 0
        for goods in user_dict['shop_cart']:
            total_amount += goods[3]
        if total_amount > user_dict['balance']:
            print('账户余额不足！')
            return False
        for goods in user_dict['shop_cart']:
            user_dict['flow'].append(
                f"{datetime.datetime.now()} 用户{user_dict['username']}购买{goods[0]}*{goods[2]}花费{goods[3]}元")
            logger.info(f"用户{user_dict['username']}购买{goods[0]}*{goods[2]}花费{goods[3]}元")
        user_dict['balance'] -= total_amount
        user_dict['shop_cart'].clear()
        save(user_dict)
        print('全部付款成功！')
        return

    # 指定商品结算
    total_amount = goods_num * user_dict['shop_cart'][goods_no][1]
    user_dict['shop_cart'][goods_no][2] -= goods_num
    user_dict['shop_cart'][goods_no][3] -= total_amount
    user_dict['balance'] -= total_amount
    if user_dict['shop_cart'][goods_no][2] == 0:
        user_dict['shop_cart'].pop(goods_no)
    user_dict['flow'].append(
        f"{datetime.datetime.now()} 用户{user_dict['username']}购买{user_dict['shop_cart'][goods_no][0]}*{user_dict['shop_cart'][goods_no][2]}花费{user_dict['shop_cart'][goods_no][2]}元")
    logger.info(
        f"用户{user_dict['username']}购买{user_dict['shop_cart'][goods_no][0]}*{user_dict['shop_cart'][goods_no][2]}花费{user_dict['shop_cart'][goods_no][2]}元")
    save(user_dict)
    print('付款成功！')
